package www.truongnha.com;
import Config.setting;
import TruongNhaLib.UserFunctions;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;

@SuppressWarnings("deprecation")
public class LoggedIn extends TabActivity {
	//Private variable:
	final UserFunctions userFunction = new UserFunctions();
	private TabHost tabHost;
	//const id for actions
	private static final int HOME_ID = 0;
	private static final int HELP_ID = 1;
	private static final int SETTING_ID = 2; 
	private static final int HANDSET = 1; 
	private static final int TABLET  = 2; 
	
	private IntentFilter intentFilter;	
	private BroadcastReceiver intentReceiver;
	private int screenType;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
	    //1.Check screen type: tablet or handset
	    int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
	    switch(screenSize) {
	    	case Configuration.SCREENLAYOUT_SIZE_XLARGE:
	    		Toast.makeText(this, "x-Large screen",Toast.LENGTH_LONG).show();
	    		screenType = TABLET;
	    		break;
	    	case Configuration.SCREENLAYOUT_SIZE_LARGE:
	            Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();
	            screenType = TABLET;
	            break;
	        case Configuration.SCREENLAYOUT_SIZE_NORMAL:
	            Toast.makeText(this, "Normal screen",Toast.LENGTH_LONG).show();
	            screenType = HANDSET;
	            break;
	        case Configuration.SCREENLAYOUT_SIZE_SMALL:
	            Toast.makeText(this, "Small screen",Toast.LENGTH_LONG).show();
	            screenType = HANDSET;
	            break;
	        default:
	            screenType = HANDSET;
	            Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();
	    }
        //2.Create action bar for this activity:
        final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
        actionBar.setHomeAction(new myAction(HOME_ID, R.drawable.ic_title_home_default));
        actionBar.setTitle("Trường Nhà" );
        actionBar.setProgressBarVisibility(View.GONE);
//        actionBar.addAction(new myAction( HELP_ID, R.drawable.ic_setting ) );
        
        //3.Custom intentReceiver
		intentReceiver = new BroadcastReceiver() {
    	    @Override
    	    public void onReceive(Context context, Intent intent) {
    	    	if(intent.getExtras().getBoolean("doneLoading"))
    	    		actionBar.setProgressBarVisibility(View.GONE);
    	    	else
    	    		actionBar.setProgressBarVisibility(View.VISIBLE);    	    		
    	    }
    	};
        intentFilter = new IntentFilter();
        intentFilter.addAction("DONE_LOADING_ACTION");
        //---register the receiver---
        registerReceiver(intentReceiver, intentFilter);
        
	    //4.Check userType from database
	    String userType = userFunction.userType( getApplicationContext() );
	    //Log.d("userType", userType );
	    
		//5. Add tads to tabActivity
	    Resources res = getResources(); // Resource object to get Drawables
		tabHost = getTabHost();  // The activity TabHost
		tabHost.setBackgroundResource(R.drawable.list_selector);
		TabHost.TabSpec spec;  // Resusable TabSpec for each tab
		Intent intent;  // Reusable Intent for each tab
		if(userType.equals("3")){//teacher
			switch (screenType) {
			case HANDSET:
				//tab1: shool + time for tablet
				intent = new Intent().setClass(this, FragAct_SchoolTime.class);
				spec = tabHost.newTabSpec("Trường học").setContent(intent);
				spec.setIndicator(createTabView(this, "Trường học", R.drawable.home_icon) );
				tabHost.addTab(spec);				
				//tab2: time
				intent = new Intent().setClass(this, FragAct_Time.class);
				spec = tabHost.newTabSpec("Lịch học").setContent(intent);
				spec.setIndicator(createTabView(this, "Lịch học", R.drawable.timetable_icon) );
				tabHost.addTab(spec);
				//tab3: profile
				intent = new Intent().setClass(this, Profile.class);
				spec = tabHost.newTabSpec("Thông tin").setContent(intent);
				spec.setIndicator(createTabView(this, "Thông tin", R.drawable.profile_icon) );
				tabHost.addTab(spec);
				break;
			case TABLET:
				//tab1: shool + time for tablet
				intent = new Intent().setClass(this, FragAct_SchoolTime.class);
				spec = tabHost.newTabSpec("Trường học")
						.setContent(intent);
				spec.setIndicator(createTabView(this, "Trường học", R.drawable.home_icon) );
				tabHost.addTab(spec);				
				//tab2: profile
				intent = new Intent().setClass(this, Profile.class);
				spec = tabHost.newTabSpec("Thông tin").setContent(intent);
				spec.setIndicator(createTabView(this, "Thông tin", R.drawable.profile_icon) );
				tabHost.addTab(spec);
				break;
			}//end switch
		} else{//student
			switch (screenType) {
			case HANDSET:
				//tab1 - mark
				intent = new Intent().setClass(this,StudentFragAct_SchoolTime.class);
				spec = tabHost.newTabSpec("Trường học").setContent(intent);
				spec.setIndicator(createTabView(this, "Trường học", R.drawable.home_icon) );
				tabHost.addTab(spec);	
				//tab2: time
				intent = new Intent().setClass(this, FragAct_Time.class);
				spec = tabHost.newTabSpec("Lịch học").setContent(intent);
				spec.setIndicator(createTabView(this, "Lịch học", R.drawable.timetable_icon) );
				tabHost.addTab(spec);
				//tab3: attend
				intent = new Intent().setClass(this, StudentFrag_Attendance.class);
				spec = tabHost.newTabSpec("Nghỉ học").setContent(intent);
				spec.setIndicator(createTabView(this, "Nghỉ học", R.drawable.timetable_icon) );
				tabHost.addTab(spec);
				//tab4: profile
				intent = new Intent().setClass(this, Profile.class);
				spec = tabHost.newTabSpec("Thông tin").setContent(intent);
				spec.setIndicator(createTabView(this, "Thông tin", R.drawable.profile_icon) );
				tabHost.addTab(spec);
				break;
			case TABLET:
				//tab1 - mark + time + attend
				intent = new Intent().setClass(this,StudentFragAct_SchoolTime.class);
				spec = tabHost.newTabSpec("Trường học").setContent(intent);
				spec.setIndicator(createTabView(this, "Trường học", R.drawable.home_icon) );
				tabHost.addTab(spec);	
				//tab2: time
				intent = new Intent().setClass(this, FragAct_Time.class);
				spec = tabHost.newTabSpec("Lịch học").setContent(intent);
				spec.setIndicator(createTabView(this, "Lịch học", R.drawable.timetable_icon) );
				tabHost.addTab(spec);
				//tab3: profile
				intent = new Intent().setClass(this, Profile.class);
				spec = tabHost.newTabSpec("Thông tin").setContent(intent);
				spec.setIndicator(createTabView(this, "Thông tin", R.drawable.profile_icon) );
				tabHost.addTab(spec);
				break;
			}//end switch
		}//end if
		// Set current tab to display: tab1 at 0th
		tabHost.setCurrentTab(0);

		//Prompt before logout:
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setMessage("Đăng xuất khỏi hệ thống ?")
	           .setCancelable(false).setIcon(R.drawable.icon).setTitle("Đăng xuất!")
	           .setPositiveButton("Có", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
						// Switching to Loggin form
						Intent i = new Intent(getApplicationContext(), TruongNhaLogin.class);
						startActivity(i);
						//finish current	 activity.
						finish();
	               }
	           })
	           .setNegativeButton("Không", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    dialog.cancel();
	               }
	           });
	    Log.d("LOG", "Post 09: 07");
		
	}//End onCreate	
	private static View createTabView(final Context context, final String text, final int resId) {
		View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
		TextView tv = (TextView) view.findViewById(R.id.text);
		ImageView icon = (ImageView) view.findViewById(R.id.icon);
		icon.setImageResource(resId);
		tv.setText(text);
		return view;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	menu.add(1, 0, 1, "Giới thiệu");
	menu.add(1, 1, 2, "Đăng xuất");
	return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(intentReceiver);
	}
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case 0:
	    	Toast.makeText(getApplication(), "TruongNha mobile version 1.0 test start service", Toast.LENGTH_LONG).show();
     	   	startIntervalService();	
        	break;
	    case 1:
	    	//Promt before logout:
			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		    builder.setMessage("Đăng xuất khỏi hệ thống?")
		           .setCancelable(true).setIcon(R.drawable.alert_icon).setTitle("Đăng xuất!")
		           .setPositiveButton("Có", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
							// Switching to Loggin form
		            	   userFunction.logoutUser(getApplicationContext());
		            	   Intent i = new Intent(getApplicationContext(), TruongNhaLogin.class);
		                   Toast.makeText(getApplicationContext(), "stop", Toast.LENGTH_SHORT).show();
		                   stopIntervalService();
		            	   startActivity(i);
		            	   //finish current	 activity.
		            	   finish();
		               }
		           })
		           .setNegativeButton("Không", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                    dialog.cancel();
		               }
		           });
	    	AlertDialog alert = builder.create();
			alert.getWindow().getAttributes().windowAnimations = R.style.DialogAnimationTopDown;
		    alert.show();
	    	break;
	    }
	    return super.onOptionsItemSelected(item);
    }
	private void startIntervalService(){
		Log.d("sendStart", "1");
		Intent intent = new Intent();
	    intent.setAction("START_SERVICE");
	    intent.putExtra("start", true);
	    getApplicationContext().sendBroadcast(intent);	
	}
	private void stopIntervalService(){
		Log.d("sendStop", "1");
		Intent intent = new Intent();
	    intent.setAction("START_SERVICE");
	    intent.putExtra("start", false);
	    getApplicationContext().sendBroadcast(intent);	  
	}
    private class myAction extends AbstractAction {
     	private int actionId;
         public myAction(int actionId, int resId) {
             super(resId);
             this.actionId = actionId;
         }

         public void performAction(View view) {
             		switch (actionId) {
 					case HOME_ID:
 						tabHost.setCurrentTab(0);
 						break;
 					case HELP_ID:			
 						break;
 					case SETTING_ID:
 			            Toast.makeText(LoggedIn.this,"Action setting", Toast.LENGTH_SHORT).show();
 						break;
 					default:
 						break;
 					}
         }//end perform

     }//end myAction class
	/**
	 * Press back button twice to exit
	 */
	private long lastPressedTime;
	private Toast toast;
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
	        switch (event.getAction()) {
	        case KeyEvent.ACTION_DOWN:
	            if (event.getDownTime() - lastPressedTime < setting.PERIOD_TWICE_TO_EXIT) {
	            	toast.cancel();
	                finish();
	            } else {
	            	toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
	            	toast.setText("Nhấn back một lần nữa để thoát | logged in");
	            	toast.show();
	                lastPressedTime = event.getEventTime();
	            }
	            return true;
	        }
	    }
	    return false;
	}

}//End class
